import room from "@/app/room"
import CreepController from "../controller"


class RoleProcessor {

    /**
     *
     * @param creep
     * @returns
     */
    static loop(creep: Creep) {

        if (creep.ticksToLive < 50 && creep.store[RESOURCE_ENERGY] > 0) {
            const storage = CreepController.findStorage(creep)
            if (storage) {
                creep.goTo(storage.pos)
                const status = creep.transfer(storage, RESOURCE_ENERGY)
                if (status == OK) {
                    if (creep.store[RESOURCE_ENERGY] == 0) {
                        creep.suicide()
                    }
                }
                return
            }
        }

        if (creep.store[RESOURCE_ENERGY] < 50 && creep.ticksToLive > 50) {
            const storage = CreepController.findStorage(creep, 0)
            if (storage) {
                creep.goTo(storage.pos)
                const status = creep.withdraw(storage, RESOURCE_ENERGY)
                if (status == ERR_NOT_IN_RANGE) {
                    return
                }
            }
            else {
                const container = CreepController.findContainer(creep, 0)
                if (container) {
                    creep.goTo(container.pos)
                    const status = creep.withdraw(container, RESOURCE_ENERGY)
                    if (status == ERR_NOT_IN_RANGE) {
                        return
                    }
                }
            }
        }
        else {
            if (creep.room.energyAvailable < creep.room.energyCapacityAvailable) {
                const storeObj = CreepController.managerFindSpawnExtension(creep)
                if (storeObj) {
                    creep.goTo(storeObj.pos)
                    creep.transfer(storeObj, RESOURCE_ENERGY)
                    return
                }
            }
            else {
                const tower = CreepController.managerFindTower(creep)
                if (tower) {
                    creep.goTo(tower.pos)
                    creep.transfer(tower, RESOURCE_ENERGY)
                    return
                }
            }

            if (creep.room[STRUCTURE_SPAWN] && creep.room[STRUCTURE_SPAWN][0]) {
                creep.goTo(creep.room[STRUCTURE_SPAWN][0].pos)
            }
        }
    }

}

export default RoleProcessor
